import React, { Component, PropTypes } from 'react';
import { Form, Icon, Input, Button, Checkbox, Modal, message, Radio, Select, Row, Col } from 'antd';
import Md5 from 'js-md5';
import { connect } from 'dva';
import $ from 'jquery';
import Style from './home.less';
import Service from '../../service';

const FormItem = Form.Item;
const RadioGroup = Radio.Group;
const formItemLayout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 18 },
};
const VerifLayout = {
  labelCol: { span: 5 },
  wrapperCol: { span: 6 },
};

var picker;
// var baseUrl='http://api.yuetengkeji.com/';
var nameEl;
var first = []; /* 省，直辖市 */
var second = []; /* 市 */
var third = []; /* 镇 */

var selectedIndex = [0, 0, 0]; /* 默认选中的地区 */

var checked = [0, 0, 0]; /* 已选选项 */

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      data: [],
      userMsg: {},
      btnText: '获取验证码',
      seconds: 60, //称数初始化
      liked: true, //获取验证码文案
      province: '请选择',
      region: '',
      city: '',
      modalIsOpen: 'none',
      areaType: 1,
      sex: 1,
      isMach: false
    }
  }
  componentWillMount() {
    const token = localStorage.getItem('token');
    this.setState({
      token: token
    })
    // this.props.queryStatistics({ token: token });
    this.props.queryProvince({ pid: 0 });
  }
  componentDidMount() {
    let info = this.props.Statistics;
    // console.log(this.props.Statistics)
    if (info) {
      if (info.province_id) {
        this.props.queryCity({ pid: info.province_id });
        this.setState({
          province: info.province_id,
          city: '',
          region: ''
        })
      }
      if (info.city_id) {
        this.props.queryRegion({ pid: info.city_id });
        this.setState({
          city: info.city_id,
          region: ''
        })
      }
      if (info.region_id) {
        this.setState({
          region: info.region_id
        })
      }
    }

    this.cityInit();

  }
  handleSubmit = (e) => {
    e.preventDefault();
    let self = this;
    const token = localStorage.getItem('token');
    // console.log(self.state.province_id)
    self.props.form.validateFields((err, values) => {
      let rex = self.regx(values);
      if (!rex) {

      } else {
        // const params = {
        //   realname: values.realname,
        //   age: values.age,
        //   sex:values.sex,
        //   adress:values.adress
        // }
        self.props.queryUpdate({
          params: {
            ...values,
            province_id: self.state.province_id,
            region_id: self.state.region_id,
            city_id: self.state.city_id,
            contact_province_id: self.state.contact_province_id,
            contact_region_id: self.state.contact_region_id,
            contact_city_id: self.state.contact_city_id,
            avatar: self.state.avatar,
            token: token
          },
          func: function () {

            message.success('注册成功!', 1.5, function () {
              self.setState({
                isMach: true
              })
              // self.context.router.push(`/1/app/myHome`);
            });
          }
        })
        // self.props.queryUser({ ...params });
        //this.props.saveUser({ id: '131341313431', user: '蛮王' })
      }
    });
  };
  /* 控制提示 */
  messageConfig() {
    message.config({
      top: 100,    // 消息距离顶部的位置
      duration: 2,     // 默认自动关闭延时，单位秒
      maxCount: 1,    // 最大显示数, 超过限制时，最早的消息会被自动关闭
    });
  }
  regx = (item) => {
    let self = this;
    if (!self.state.avatar) {
      message.error('请上传头像');
      self.messageConfig();
      return false
    }
    if (!item.realname || item.realname == 'undefined') {
      message.error('请填写姓名');
      self.messageConfig();
      return false
    }
    if (!item.id_card || item.id_card == 'undefined') {
      message.error('请填写身份证');
      self.messageConfig();
      return false
    }

    if (!item.mobile || item.mobile == 'undefined') {
      message.error('请填写紧急联系人手机号');
      self.messageConfig();
      return false
    }
    // console.log(self.state.param)
    if (!self.state.province_id) {
      message.error('请选择城市');
      self.messageConfig();
      return false
    }
    if (!item.address || item.address == 'undefined') {
      message.error('请填写具体地址');
      self.messageConfig();
      return false
    }

    if (!item.number || item.number == 'undefined') {
      message.error('请填写车牌号');
      self.messageConfig();
      return false
    }
    if (!item.device_no || item.device_no == 'undefined') {
      message.error('请填写车辆编号');
      self.messageConfig();
      return false
    }
    if (!item.imei || item.imei == 'undefined') {
      message.error('请填写设备编号');
      self.messageConfig();
      return false
    }

    if (!item.contact_realname || item.contact_realname == 'undefined') {
      message.error('请填写紧急联系人');
      self.messageConfig();
      return false
    }

    if (!item.contact_id_card || item.contact_id_card == 'undefined') {
      message.error('请填写紧急联系人身份证');
      self.messageConfig();
      return false
    }
    if (!item.contact_mobile || item.contact_mobile == 'undefined') {
      message.error('请填写紧急联系电话');
      self.messageConfig();
      return false
    }
    if (!self.state.contact_province_id) {
      message.error('请选择紧急联系人城市');
      self.messageConfig();
      return false
    }
    if (!item.contact_address) {
      message.error('请选择紧急联系人详情地址');
      self.messageConfig();
      return false
    }



    return true
  }
  goToLoginFun = (e) => {
    this.context.router.push(`/login`)
  };
  // 获取验证码
  sendCode = () => {
    let phone = this.props.form.getFieldValue('phone');
    if (!phone) {
      return message.error('请输入手机号');
    }
    const params = {
      phone: phone,
      getCode: (code) => {
        console.log(code);
        codepage();
      }
    }
    this.props.querySendCode({ ...params });

  }
  // 关闭弹出框
  handleCancel = e => {
    this.setState({
      [e]: false
    });
  };
  codepage = () => {
    let siv = setInterval(() => {
      this.setState({
        liked: false,
        seconds: this.state.seconds - 1,
      }, () => {
        if (this.state.seconds == 0) {
          clearInterval(siv);
          this.setState({
            liked: true,
            seconds: 60
          })
        }
      });
    }, 1000);
  }
  myhomeFun = () => {
    this.context.router.push(`/1/app/myHome`);
  }
  handleChangeCity = (value) => {
    this.props.queryCity({ pid: value });
    this.setState({
      province: value,
      city: '请选择',
      region: '请选择'
    })
  }
  handleChangeRegion = (value) => {
    this.props.queryRegion({ pid: value });
    this.setState({
      city: value,
      region: '请选择'
    })
    // console.log(value);
  }
  handleChange = (value) => {
    this.setState({
      region: value
    })
    // console.log(value);
  }
  provice(pid, level, arr, type, ) {
    var self = this;
    $.ajax({
      type: "POST",
      url: `${Service.baseUrl}/tool/area`,
      data: { level: level, pid: pid },
      dataType: "json",
      async: false,
      success: function (data) {
        if (data.code == 200) {
          if (type == 1) {
            self.creatList(data.data, arr);
          } else if (type == 2) {
            if (data.data) {
              self.creatList(data.data, second);
              // 请求三级数据
              var pids = data.data[0].id;
              self.provice(pids, 3, third, 3);
            } else {
              second = [{ text: '', value: 0 }];
              third = [{ text: '', value: 0 }];
              checked[1] = 0;
              checked[2] = 0;
            }
          } else if (type == 3) {
            if (data.data) {
              self.creatList(data.data, third);
            } else {
              third = [{ text: '', value: 0 }];
              checked[2] = 0;
            }
          } else if (type == 4) {
            if (data.data) {
              self.creatList(data.data, third);
              picker.refillColumn(2, third);
              picker.scrollColumn(2, 0)
            } else {
              third = [{ text: '', value: 0 }];
              checked[2] = 0;
              picker.refillColumn(2, third);
              picker.scrollColumn(2, 0)
            }
          }

        }
      }
    });
  }
  cityInit = () => {
    var self = this;
    nameEl = document.getElementById('citybtn');
    self.provice(0, 1, first, 1);
    // self.provice(1, 1, second, 2);
    self.provice(2, 3, third, 3);
    // self.creatList(city, first);

    if (city[selectedIndex[0]].hasOwnProperty('sub')) {
      self.provice(1, 1, second, 2);
      // self.creatList(city[selectedIndex[0]].sub, second);
    } else {
      second = [{ text: '', value: 0 }];
    }

    // if (city[selectedIndex[0]].sub[selectedIndex[1]].hasOwnProperty('sub')) {
    //   self.provice(2, 3, third, 3);
    //   // self.creatList(city[selectedIndex[0]].sub[selectedIndex[1]].sub, third);
    // } else {
    //   third = [{ text: '', value: 0 }];
    // }

    picker = new Picker({
      data: [first, second, third],
      selectedIndex: selectedIndex,
      title: '地址选择'
    });


    picker.on('picker.select', function (selectedVal, selectedIndex) {
      // console.log(first)
      // console.log(first[selectedIndex[0]])
      var text1 = first[selectedIndex[0]].text;
      var text2 = second[selectedIndex[1]].text;
      var text3 = third[selectedIndex[2]] ? third[selectedIndex[2]].text : '';
      //  执行列表搜索方法
      // console.log(text1 + ' ' + text2 + ' ' + text3)
      // console.log(self.props.form.setFieldsValue('provinceCity',text1 + ' ' + text2 + ' ' + text3));
      // $('#citybtn').val(text1 + ' ' + text2 + ' ' + text3) ;
      if (self.state.areaType == 1) {
        self.setState({
          province_id: first[selectedIndex[0]].value,
          city_id: second[selectedIndex[1]].value,
          region_id: third[selectedIndex[2]] ? third[selectedIndex[2]].value : '',
          provinceCity: text1 + text2 + text3
        })
        // self.props.form.setFieldsValue({ 'provinceCity': text1 + text2 + text3 });
      } else {
        self.setState({
          contact_province_id: first[selectedIndex[0]].value,
          contact_city_id: second[selectedIndex[1]].value,
          contact_region_id: third[selectedIndex[2]] ? third[selectedIndex[2]].value : '',
          provinceCity1: text1 + text2 + text3
        })
        // self.props.form.setFieldsValue({ 'provinceCity1': text1 + text2 + text3 });
      }
    });
    picker.on('picker.change', function (index, selectedIndex) {
      // console.log(1111)
      if (index === 0) {
        self.firstChange(index, selectedIndex);
      } else if (index === 1) {
        self.secondChange(index, selectedIndex);
      }
    })

    // nameEl.addEventListener('click', function () {
    //   picker.show();
    // });

  }

  creatList(obj, list) {
    obj.forEach(function (item, index, arr) {
      var temp = new Object();
      temp.text = item.name;
      temp.value = item.id;
      list.push(temp);
    })
  }
  firstChange(index, selectedIndex) {
    var self = this;
    second = [];
    third = [];
    checked[0] = selectedIndex;
    // var firstCity = city[selectedIndex];
    // console.log(firstCity)
    // if (firstCity.hasOwnProperty('sub')) {
    //   self.creatList(firstCity.sub, second);

    //   var secondCity = city[selectedIndex].sub[0]
    //   if (secondCity.hasOwnProperty('sub')) {
    //     self.creatList(secondCity.sub, third);
    //   } else {
    //     third = [{ text: '', value: 0 }];
    //     checked[2] = 0;
    //   }
    // } else {
    //   second = [{ text: '', value: 0 }];
    //   third = [{ text: '', value: 0 }];
    //   checked[1] = 0;
    //   checked[2] = 0;
    // }

    var firstCity = first;
    // console.log(first);
    var pid = first[selectedIndex].value;
    self.provice(pid, 1, second, 2);

    picker.refillColumn(1, second);
    picker.refillColumn(2, third);
    picker.scrollColumn(1, 0)
    picker.scrollColumn(2, 0)
  }
  secondChange(index, selectedIndex) {
    var self = this;
    third = [];
    checked[1] = selectedIndex;
    var first_index = checked[0];
    // if (city[first_index].sub[selectedIndex].hasOwnProperty('sub')) {
    //   var secondCity = city[first_index].sub[selectedIndex];
    //   self.creatList(secondCity.sub, third);
    //   picker.refillColumn(2, third);
    //   picker.scrollColumn(2, 0)
    // } else {
    //   third = [{ text: '', value: 0 }];
    //   checked[2] = 0;
    //   picker.refillColumn(2, third);
    //   picker.scrollColumn(2, 0)
    // }

    var pid = second[selectedIndex].value;
    self.provice(pid, 3, third, 4);
  }
  pickAdressShow = (type) => {
    this.setState({
      areaType: type
    })
    picker.show();
  }
  // 上传
  fileUpload(e) {
    const token = localStorage.getItem('token');
    var self = this;
    $('#y-upload').ajaxSubmit({
      url: `${Service.baseUrl}/tool/upload`,
      type: 'POST',
      enctype: 'multipart/form-data',
      dataType: 'json',
      success: function (data) {
        if (data.code == 200) {
          var imgSrc = data.data;
          // console.log(imgSrc);
          self.setState({
            avatar: imgSrc
          })

        } else {
          //上传失败
          if (data.error_code != 8001) { // 8001 上传图片为空的时候 为了解决ie同时上传两次情况
            // that.messageConfig(); // 提示统一设置

            if (data.error_code == 1001) {
              message.error('请先登录', 1.5, function () {
                self.context.router.push(`/register`);
              });
            } else {
              message.warning(<span>{data.error}</span>);
            }
          }

        }

      },

      error: function () {
        message.error(<span>上传图片不能为空</span>);
      }
    })
    // }
  }
  handleMouseOver = (e) => {
    this.setState({
      modalIsOpen: 'block',
    })
  }
  handleMouseOut = (e) => {
    this.setState({
      modalIsOpen: 'none',
    })

  }
  onChange = (e) => {
    this.setState({
      sex: e.target.value,
    });
  };
  render() {
    const { Statistics, region, city, province, data } = this.props;
    const content = data || {};
    // console.log(province);
    // console.log(city);
    // console.log(region);
    const { getFieldDecorator } = this.props.form;
    return (
      <div className={Style.wrap}>
        <div className={Style.headWrap + ' ' + Style.headWrapEdit}>
          <div className={Style.navTitle}>
            {/* <Icon className={Style.arrow} type="left" theme="outlined" onClick={this.myhomeFun} /> */}
            快速通道
            {/* <span className={Style.arrow + ' ' + Style.arrowText} onClick={this.handleSubmit}>提交</span> */}
          </div>
        </div>
        <div className={Style.grayH}></div>
        <div className={Style.authBoxs + ' ' + Style.authBoxsEdit}>
          <div className={Style.content}>
            <div className={Style.inputBox}>
              <Form className="login-form">
                <FormItem
                  label="头像"
                  labelCol={{ span: 6 }}
                  wrapperCol={{ span: 12 }}
                >
                  <div className={Style.avatarWrap} onMouseLeave={this.handleMouseOut}>
                    {this.state.avatar &&
                      <div className={Style.avatarimgWrap}>
                        <img src={`${Service.baseUrl}` + '/' + this.state.avatar} className={Style.pic} id="fileUploadImg" onMouseOver={this.handleMouseOver} />
                        <a href="javascript:;" className={Style.fileUploadImg} id="fileUpload" style={{ display: this.state.modalIsOpen }}>
                          <form id="y-upload" className={Style.fileUpload} method="post" encType="multipart/form-data">
                            <input type="file" className={Style.picFile} title=" " name="image" value="" onChange={(e) => this.fileUpload(e)} />
                            <input name='token' value={this.state.token} type='hidden' />
                          </form>
                        </a>
                      </div>
                    }
                    {!this.state.avatar &&
                      <a href="javascript:;" className={Style.fileUploadImg}>
                        <form id="y-upload" className={Style.fileUpload} method="post" encType="multipart/form-data">
                          <input type="file" className={Style.picFile} title=" " name="image" value="" onChange={(e) => this.fileUpload(e)} />
                          <input name='token' value={this.state.token} type='hidden' />
                        </form>
                      </a>
                    }
                  </div>
                </FormItem>
                <FormItem label='姓名:' {...formItemLayout}>
                  {getFieldDecorator('realname', {
                    initialValue: Statistics && Statistics.realname || '',
                  })(
                    <Input autoComplete="realname" />
                    )}
                </FormItem>
                <FormItem label='年龄:' {...formItemLayout}>
                  {getFieldDecorator('age', {
                    initialValue: Statistics && Statistics.age || '',
                  })(
                    <Input autoComplete="age" />
                    )}
                </FormItem>
                <FormItem label='性别:' {...formItemLayout}>
                  {getFieldDecorator('sex', {
                    initialValue: Statistics && Statistics.sex || '',
                  })(
                    <RadioGroup onChange={this.onChange} defaultValue={1} value={this.state.sex}>
                      <Radio value={1}>男</Radio>
                      <Radio value={2}>女</Radio>
                    </RadioGroup>
                    )}
                </FormItem>
                <FormItem label='身份证:' {...formItemLayout}>
                  {getFieldDecorator('id_card', {
                    initialValue: Statistics && Statistics.id_card || '',
                  })(
                    <Input placeholder="身份证" autoComplete="id_card" />
                    )}
                </FormItem>
                <FormItem label='手机号:' {...formItemLayout}>
                  {getFieldDecorator('mobile', {
                    initialValue: Statistics && Statistics.sex || '',
                  })(
                    <Input placeholder="手机号" autoComplete="mobile" />
                    )}
                </FormItem>
                <FormItem label='所在地址:' {...formItemLayout}>

                  <Input placeholder="请选择所在地址" value={this.state.provinceCity} ref='provinceCity' autoComplete="provinceCity" onFocus={this.pickAdressShow.bind(this, 1)} id='citybtn' />


                </FormItem>
                {/* <FormItem label='城市选择:' {...formItemLayout}>
                  {getFieldDecorator('id_card', {
                    initialValue: Statistics && Statistics.id_card || '',
                    rules: [{ required: true, message: '城市选择' }]
                  })(
                    <Input placeholder="城市选择" autoComplete="id_card" />
                    )}
                </FormItem> */}

                {/* {province && this.state.province &&
                  <FormItem label='省:' {...formItemLayout}>
                    {getFieldDecorator('province', {
                      initialValue: this.state.province || '',
                      rules: [{ required: true, message: '请选择' }]
                    })(
                      <Select defaultValue={this.state.province} style={{ width: 120 }} onChange={this.handleChangeCity}>
                        {
                          province.map((item, i) => (
                            <Option key={i} value={item.id}>{item.name}</Option>
                          ))
                        }

                      </Select>
                      )}
                  </FormItem>
                }
                {city && this.state.city &&
                  <FormItem label='市:' {...formItemLayout}>
                    {getFieldDecorator('city', {
                      initialValue: this.state.city || '',
                      rules: [{ required: true, message: '请选择' }]
                    })(
                      <Select defaultValue={this.state.city} style={{ width: 120 }} onChange={this.handleChangeRegion}>
                        {
                          city.map((item, i) => (
                            <Option key={i} value={item.id}>{item.name}</Option>
                          ))
                        }

                      </Select>
                      )}
                  </FormItem>
                }
                {region && this.state.region &&
                  <FormItem label='区:' {...formItemLayout}>

                    {getFieldDecorator('region', {
                      initialValue: this.state.region || '',
                      rules: [{ required: true, message: '请选择' }]
                    })(
                      <Select defaultValue={this.state.region} style={{ width: 120 }} onChange={this.handleChange}>
                        {
                          region.map((item, i) => (
                            <Option key={i} value={item.id}>{item.name}</Option>
                          ))
                        }

                      </Select>
                      )}
                  </FormItem>
                } */}

                <FormItem label='详细地址' {...formItemLayout}>
                  {getFieldDecorator('address', {
                    initialValue: Statistics && Statistics.address || '',
                  })(
                    <Input placeholder="请输入现居地址" autoComplete="address" />
                    )}
                </FormItem>
                <FormItem
                  label="车辆编号"
                  labelCol={{ span: 6 }}
                  wrapperCol={{ span: 18 }}
                >
                  {getFieldDecorator('device_no', {
                    initialValue: '',
                  })(
                    <Input value='' />
                    )}
                </FormItem>
                <FormItem
                  label="车辆品牌"
                  labelCol={{ span: 6 }}
                  wrapperCol={{ span: 18 }}
                >
                  {getFieldDecorator('brand', {
                    initialValue: '',
                  })(
                    <Input value='' />
                    )}
                </FormItem>
                <FormItem
                  label="设备编号"
                  labelCol={{ span: 6 }}
                  wrapperCol={{ span: 18 }}
                >
                  {getFieldDecorator('imei', {
                    initialValue: ''
                  })(
                    <Input value='' />
                    )}
                </FormItem>
                <FormItem
                  label="车牌号"
                  labelCol={{ span: 6 }}
                  wrapperCol={{ span: 18 }}
                >
                  {getFieldDecorator('number', {
                    initialValue: ''
                  })(
                    <Input value='' />
                    )}
                </FormItem>


                {/* <div className={Style.borderd}> */}
                {/* </div> */}
                <h3 style={{ paddingBottom: '5px' }}>紧急联系人信息：</h3>

                <FormItem
                  label="姓名"
                  labelCol={{ span: 6 }}
                  wrapperCol={{ span: 18 }}
                >
                  {getFieldDecorator('contact_realname', {
                    initialValue: ''
                  })(
                    <Input value='' />
                    )}
                </FormItem>
                <FormItem
                  label="身份证"
                  labelCol={{ span: 6 }}
                  wrapperCol={{ span: 18 }}
                >
                  {getFieldDecorator('contact_id_card', {
                    initialValue: ''
                  })(
                    <Input value='' />
                    )}
                </FormItem>
                <FormItem
                  label="联系电话"
                  labelCol={{ span: 6 }}
                  wrapperCol={{ span: 18 }}
                >
                  {getFieldDecorator('contact_mobile', {
                    initialValue: ''
                  })(
                    <Input value='' />
                    )}
                </FormItem>


                <FormItem
                  label="城市筛选"
                  labelCol={{ span: 6 }}
                  wrapperCol={{ span: 18 }}
                >

                  <Input id='citybtn1' value={this.state.provinceCity1} ref='provinceCity1' autoComplete="provinceCity1" onFocus={this.pickAdressShow.bind(this, 2)} />

                  {/* <Cascader options={selectBank} onChange={this.onChangeTreeContact} placeholder="请选择具体区域" /> */}

                </FormItem>
                <FormItem
                  label="地址"
                  labelCol={{ span: 6 }}
                  wrapperCol={{ span: 18 }}
                >
                  {getFieldDecorator('contact_address', {
                    initialValue: ''
                  })(
                    <Input />
                    )}
                </FormItem>
                <Form.Item>
                  <Button type="primary" htmlType="submit" className="login-form-button" onClick={this.handleSubmit}>
                    提交
                </Button>
                </Form.Item>
              </Form>

            </div>

          </div>
        </div>

        <Modal
          title=""
          visible={this.state.isMach}
          onOk={this.exchangeOk}
          onCancel={this.handleCancel.bind(this, "isMach")}
          footer={null}
          centered={true}
          wrapClassName="modalBottomWrap"
        >
          <div className={Style.buyWrap}>
            <h2>注册成功
            {/* <span className={Style.close} onClick={this.handleCancel.bind(this, "isMach")}>
                <Icon type="close" />
              </span> */}
            </h2>
            <div className={Style.line}></div>



            <div className={Style.toPay + ' ' + Style.tomach}></div>
            {/* <div className={Style.grayline}></div> */}
            <div className={Style.confirmBtn} onClick={this.handleCancel.bind(this, "isMach")} >
              修改信息
            </div>
          </div>

        </Modal>
      </div >
    )
  }
}

App.contextTypes = {
  router: React.PropTypes.object
}

function mapStateToProps(state, ownProps) {
  return {
    // data: state.userManage.saveAdressSeslect,
    Statistics: state.myHome.Statistics,
    data: state.myHome.city,
    province: state.myHome.province,
    region: state.myHome.region,
    loading: !!state.loading.global
  }
}
function dispatchToProps(dispatch) {
  return {
    queryStatistics(payload, params) {
      dispatch({ type: 'myHome/queryStatistics', payload })
    },
    queryProvince(payload, params) {
      dispatch({
        type: 'myHome/queryProvince',
        payload
      })
    },
    queryCity(payload, params) {
      dispatch({
        type: 'myHome/queryCity',
        payload
      })
    },
    queryRegion(payload, params) {
      dispatch({
        type: 'myHome/queryRegion',
        payload
      })
    },
    queryUpdate(payload, params) {
      dispatch({
        type: 'myHome/update',
        payload
      })
    }
  }
}
export default connect(mapStateToProps, dispatchToProps)(Form.create()(App));
